<?php

namespace app\shop\controller;

use think\Controller;

class Product extends Controller
{
    protected $busid;
    protected $Business;

    public function _initialize()
    {
        // 继承父类
        parent::_initialize();
        $this->BusinessModel = model('Business.Business');
        $this->ProductModel = model('Product.Product');
        $this->TypeModel = model('Product.Type');
        $this->PropModel = model('Product.Prop');
        $this->RelationModel = model('Product.Relation');
        $this->CartModel = model('Product.Cart');
        $this->CollectionModel = model('Business.Collection');
        $this->OrderProductModel = model('Product.OrderProduct');
    }

    public function index()
    {
        if ($this->request->isPost())
        {
            // header('Content-Type: application/json');
            // echo json_encode($_SERVER);
            // exit();
            
            $newlist = $this->ProductModel->where(['flag' => '1', 'status' => '1'])->order('createtime desc')->limit(8)->select();

            $hostlist =  $this->ProductModel->where(['flag' => '2', 'status' => '1'])->order('createtime desc')->limit(5)->select();

            $data = [
                'newlist' => $newlist,
                'hostlist' => $hostlist
            ];

            // var_dump($data);exit;

            $this->success('', '', $data);
        }
    }

    // 分类
    public function type()
    {
        if ($this->request->isPost())
        {
            $data = $this->TypeModel->field('id as value,name as text')->select();

            $this->success('', '', $data);
        }
    }

    // 列表
    public function lists()
    {
        if ($this->request->isPost())
        {
            $keywords = $this->request->param('keywords', '', 'trim');
            $flag = $this->request->param('flag', 0, 'trim');
            $order = $this->request->param('order', 'createtime', 'trim');
            $sort = $this->request->param('sort', 'desc', 'trim');
            $typeid = $this->request->param('typeid', 0, 'trim');

            $where = [];

            if(!empty($keywords))
            {
                $where['name'] = ['LIKE', "%$keywords%"];
            }

            if($flag > 0)
            {
                $where['flag'] = $flag;
            }

            if($typeid > 0)
            {
                $where['typeid'] = $typeid;
            }

            $data = $this->ProductModel->where($where)->order("$order $sort")->select();

            $this->success('', '', $data);
        }
    }

    // 详情
    public function info()
    {
        if ($this->request->isPost())
        {
            $proid = $this->request->param('proid', 0, 'trim');
            $busid = $this->request->param('busid', 0, 'trim');

            $productinfo = $this->ProductModel->find($proid); 

            if(!$productinfo)
            {
                $this->error('产品不存在');
                exit;
            }

            $productinfo['count'] = null;
            $productinfo['collection'] = 'star-o';

            $business = $this->BusinessModel->find($busid);

            if($business)
            {
                $cartcount = $this->CartModel->where(['busid' => $busid])->count();

                $productinfo['count'] = $cartcount ? $cartcount : null;

                $collection = $this->CollectionModel->where(['busid' => $busid,'status' => 'product', 'collectid' => $proid])->find();

                $productinfo['collection'] = $collection ? 'star' : 'star-o';
            }

            $properties = [];
            $list = [];

            // 查找商品规格属性
            $attrid = $this->RelationModel->where(['proid' => $proid])->group('propid')->column('propid');
            $attrs = $this->PropModel->where('id', 'IN', $attrid)->column('id, title');

            if ($attrs)
            {
                foreach ($attrs as $key => $item)
                {
                    $properties[$key] = [
                        'k_id' => $key,
                        'k' => $item,
                        'is_multiple' =>  false, // 是否可多选
                        'v' => []
                    ];
                }
            }

            //查找商品规格列表
            $relationlist = $this->RelationModel->where(['proid' => $proid])->select();

            if ($relationlist && $properties)
            {
                foreach ($relationlist as $item)
                {
                     $properties[$item['propid']]['v'][] = [
                        'id' => $item['id'], // 属性值id
                        'name' => $item['value'], // 属性值名
                        'price' => (float)bcmul($item['price'], 100), //属性值加价 前端显示的是分单位,
                        'text_status' => '1' // 属性启用/禁用状态 0 - 禁用，1 - 启用
                    ];
                }
            }

            // sku,list存储属性
            foreach ($properties as $item)
            {
                $list[] = [
                    'id' =>  $item['k_id'], // skuId
                    'price' =>  (float)bcmul($productinfo['price'], 100), // 价格（单位分）
                    'stock_num' =>  $productinfo['stock'] // 当前 sku 组合对应的库存
                ];
            }

            $sku = [
                'tree' => [],
                'price' => $productinfo['price'], //默认价格（单位元）
                'stock_num' => $productinfo['stock'],// 商品总库存
                'list' => $list
            ];

            $data = [
                'info' => $productinfo,
                'sku' => $sku,
                'properties' => $properties
            ];

            $this->success('', '', $data);
        }
    }

    // 收藏商品
    public function collect() {
        if ($this->request->isPost()) {
            $busid = $this->request->param('busid', 0, 'trim');
            $collectid = $this->request->param('proid', 0, 'trim');

            $data = [
                'busid' => $busid,
                'collectid' => $collectid,
                'status' => 'product',
            ];

            $result = $this->CollectionModel->save($data);

            if ($result) {
                $this->success('收藏成功');
            } else {
                $this->error('收藏失败');
            }
        }
    }

    // 取消收藏
    public function cancelCollect() {
        if ($this->request->isPost()) {
            $busid = $this->request->param('busid', 0, 'trim');
            $collectid = $this->request->param('proid', 0, 'trim');
        }

        $data = [
            'busid' => $busid,
            'collectid' => $collectid,
            'status' => 'product',
        ];

        $result = $this->CollectionModel->where($data)->delete();

        if ($result != 0) {
            $this->success('取消收藏成功');
        } else {
            $this->error('取消收藏失败'. $result);
        }
    }

    // 评价列表
    public function rateInfo()
    {
        if ($this->request->isPost()) {
            $proid  = $this->request->param('proid', 0, 'trim');
            $busid = $this->request->param('busid', 0, 'trim');

            $business = $this->BusinessModel->find($busid);

            // 组装商品评论查询条件
            $where = [
                'proid' => $proid,
            ];

            $busRate = [];
            $orderpro = $this->OrderProductModel->with('business')->where($where)->whereNotNull('rate')->select();

            if (!$orderpro) {
                $this->error('商品评价不存在');
                exit;
            }     

            // 组装评论信息
            $data = [
                'busRate' => $busRate,
                'orderpro' => $orderpro,
            ];

            // 返回响应数据
            if ($data) {
                $this->success('', '', $data);
            } else {
                $this->error('评价信息不存在');
            }
        }
    }

    // 商品榜单
    public function rank()
    {
        if ($this->request->isPost()) {
            
            $orderpro = $this->OrderProductModel
                ->with('product')
                ->field('COUNT(proid) AS pro_count')
                ->group('proid')
                ->order('pro_count desc')
                ->select();

            if (!$orderpro) {
                $this->error('商品评价不存在');
                exit;
            } else {
                $this->success('', '', $orderpro);
            }
        }
    }
}
